package cn.samler.shopapi.Controller;

import cn.samler.shopapi.Annotation.IgnoreTokenCheck;
import cn.samler.shopapi.Model.Sys.ServiceResult;
import cn.samler.shopapi.Model.Request.User.LoginModel;
import cn.samler.shopapi.Model.Request.User.CaptchaModel;
import cn.samler.shopapi.Model.Sys.Response;
import cn.samler.shopapi.Entity.User;
import cn.samler.shopapi.Service.UploadService;
import cn.samler.shopapi.Service.UserService;
import cn.samler.shopapi.Utils.IpUtil;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
    private final UserService userService;
    private final UploadService uploadService;

    UserController(UserService userService, UploadService uploadService) {
        this.userService = userService;
        this.uploadService = uploadService;
    }

    @PostMapping("login")
    @IgnoreTokenCheck
    public Response login(@RequestBody @Validated LoginModel user) {
        log.debug("user login: " + user);

        if (user.getIsVcodeLogin()) {
            //使用短信验证码登录
            ServiceResult result = userService.loginForVerifyCode(user.getUsername(), user.getVcode());
            if (result.isSuccess()) {
                JSONObject json = new JSONObject();
                json.put("access_token", userService.createToken((User) result.getData()));

                return Response.success("登录成功", json);
            }

            return Response.failure("验证码错误");
        } else {
            //使用密码登录
            ServiceResult result = userService.loginForPassword(user.getUsername(), user.getPassword());
            if (result.isSuccess()) {
                JSONObject json = new JSONObject();
                json.put("access_token", userService.createToken((User) result.getData()));

                return Response.success("登录成功", json);
            }

            return Response.failure("账号或密码错误");
        }
    }

    @PostMapping("sendSms")
    @IgnoreTokenCheck
    public Response sendSms(HttpServletRequest request, @RequestBody CaptchaModel captcha) {
        switch (userService.sendSms(captcha.getUsername(), captcha.getTicket(), captcha.getRandstr(), IpUtil.getIpAddr(request))) {
            case 0:
                return Response.success("发送成功");
            case 1:
                return Response.failure("发送失败");
            case 2:
                return Response.failure("验证失败");
            default:
                return Response.failure("未知错误");
        }
    }

    /**
     * 获取用户信息
     *
     * @param request
     * @return User
     */
    @GetMapping("info")
    public Response getInfo(HttpServletRequest request) {
        return Response.success(userService.getInfo((User) request.getAttribute("current_user")));
    }

    @PostMapping("setPassword")
    public Response setPassword(HttpServletRequest request, @RequestBody JSONObject json) {
        if (userService.setPassword((User) request.getAttribute("current_user"), (String) json.getOrDefault("password", null)))
            return Response.success("设置成功");

        return Response.failure("设置失败");
    }


    /**
     * 头像上传
     * 目前使用腾讯COS进行图片文件的存储，未来会更新包括本地存储在内的更多存储方式
     *
     * @param request request对象
     * @param file    图片文件
     * @return
     */
    @PostMapping("avatar_upload")
    public Response uploadAvatar(HttpServletRequest request, @RequestParam("file") MultipartFile file) {
        if (file == null || file.isEmpty()) return Response.failure("上传失败，文件为空");
        String originalFilename = file.getOriginalFilename();
        try {
            // 尝试对文件进行转换，未抛出异常则是图片文件
            ImageIO.read(file.getInputStream());

            String fileName = "uploads/" + UUID.randomUUID() + originalFilename.substring(originalFilename.lastIndexOf("."));
            ServiceResult result = uploadService.upload(file.getInputStream(), fileName);
            if (result.isSuccess()) {
                userService.updateAvatar((User) request.getAttribute("current_user"), result.getData().toString());
                return Response.success("上传成功", result.getData());
            }

            return Response.failure("上传失败", result.getData());
        } catch (IOException e) {
            return Response.failure("非图片文件", e.toString());
        }
    }
}
